from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_required, get_jwt_identity, get_jwt
from flask_mail import Message
import sys
sys.path.append("/")
from app.services.user import UserService
from app.services.auth import AuthService
from app.schemas.user import password_reset_schema
from app.extensions import mail



auth_bp = Blueprint('auth', __name__, url_prefix='/auth')


#用户登录
@auth_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()

    user, error = AuthService.authenticate(data.get('username'), data.get('password'))
    if error:
        return jsonify({"error": error}), 401

    access_token, refresh_token = AuthService.generate_tokens(user)
    return jsonify({
        "access_token": access_token,
        "refresh_token": refresh_token
    }), 200
#发送的json{
    #"username": "susan",
    #"password": "123456"
#}
#返回的token{
  #"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzMzNzU2NywianRpIjoiNzdjNDQ0ZjgtZTdjOC00ODAzLWI0NGQtMWU3OTRiMTMxY2NkIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IjMiLCJuYmYiOjE3NTMzMzc1NjcsImNzcmYiOiI5YmNkNGQ2Yy0xNDkxLTRjYzItOTgyMC04ZjU2N2YxNmJkYjMiLCJleHAiOjE3NTMzNDExNjcsInVzZXJuYW1lIjoic3VzYW4iLCJpc19hZG1pbiI6ZmFsc2UsInJvbGVzIjpbIm5vcm1hbF91c2VyIl19.V1sA_1d-Q0TaFl-RE1-D2AesPSrfLb568G_M_NjeOis",
  #"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzMzNzU2NywianRpIjoiZjZmM2VjNjEtMzVlNC00MzM1LWJkOGUtM2YxZDlmNTg0MWQ0IiwidHlwZSI6InJlZnJlc2giLCJzdWIiOjMsIm5iZiI6MTc1MzMzNzU2NywiY3NyZiI6ImU4YzQwMmE1LWUwNTktNGIxNi1hZGNlLTlmZjQ0MTQ4OTczYiIsImV4cCI6MTc1Mzk0MjM2N30.Yclxg8VuhCmZMyeIT_celPJzjxqKjlRMJif2Vk_k6Tc"
#}




#刷新token
@auth_bp.route('/refresh', methods=['POST'])
@jwt_required(refresh=True)
def refresh():
    current_user_id = get_jwt_identity()
    user = UserService.get_user_by_id(current_user_id)
    if not user or not user.is_active:
        return jsonify({"error": "Invalid user"}), 401

    access_token = create_access_token(identity=str(current_user_id),  additional_claims={
                "username": user.username,
                "is_admin": user.is_admin,
                "roles": [role.name for role in user.roles]
            })
    refresh_token = create_refresh_token(identity=str(current_user_id))
    return jsonify({"access_token": access_token, "refresh_token": refresh_token}), 200

#发出的refresh token Headers  Authorization  Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzMzNzU2NywianRpIjoiNzdjNDQ0ZjgtZTdjOC00ODAzLWI0NGQtMWU3OTRiMTMxY2NkIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IjMiLCJuYmYiOjE3NTMzMzc1NjcsImNzcmYiOiI5YmNkNGQ2Yy0xNDkxLTRjYzItOTgyMC04ZjU2N2YxNmJkYjMiLCJleHAiOjE3NTMzNDExNjcsInVzZXJuYW1lIjoic3VzYW4iLCJpc19hZG1pbiI6ZmFsc2UsInJvbGVzIjpbIm5vcm1hbF91c2VyIl19.V1sA_1d-Q0TaFl-RE1-D2AesPSrfLb568G_M_NjeOis

#返回的token{
 #"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzM0MTg2MCwianRpIjoiOGViOWM2YzAtNjM5NS00NjMwLTgwODItYmQ2ZDRiNjg0MmI3IiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IjMiLCJuYmYiOjE3NTMzNDE4NjAsImNzcmYiOiI4Mjk3Zjg1MC1mNjQxLTQwZTEtYTJkOS00OWUzYTc4MmM3MWMiLCJleHAiOjE3NTMzNDU0NjAsInVzZXJuYW1lIjoic3VzYW4iLCJpc19hZG1pbiI6ZmFsc2UsInJvbGVzIjpbIm5vcm1hbF91c2VyIl19.tphbYRIuqEPGSa8XMblDC9NO3S6O5MAitnj02vjwXPA",
  #"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzM0MTg2MCwianRpIjoiZTIxM2UwMzEtYWUzNy00MDBjLTgyYjgtNTQ4Y2U4NWFmOTVjIiwidHlwZSI6InJlZnJlc2giLCJzdWIiOiIzIiwibmJmIjoxNzUzMzQxODYwLCJjc3JmIjoiNmI3M2I3ZWUtNDFlMC00ZDU5LTllMGQtNjA5NTY4MjU5YThmIiwiZXhwIjoxNzUzOTQ2NjYwfQ.aqn1nXuERydr5hI7AJ0sgSzWbh2MdjQqJI_2jdyU_Tg"
#}



#用户登出
@auth_bp.route('/logout', methods=['POST'])
@jwt_required(verify_type=False)
def logout():
    token = get_jwt()
    jti = token['jti']

    if UserService.revoke_token(jti):
        return jsonify({"message": "Token revoked"}), 200
    return jsonify({"error": "Failed to revoke token"}), 500

#发出的access token Headers  Authorization  Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc1MzMzNzU2NywianRpIjoiNzdjNDQ0ZjgtZTdjOC00ODAzLWI0NGQtMWU3OTRiMTMxY2NkIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6IjMiLCJuYmYiOjE3NTMzMzc1NjcsImNzcmYiOiI5YmNkNGQ2Yy0xNDkxLTRjYzItOTgyMC04ZjU2N2YxNmJkYjMiLCJleHAiOjE3NTMzNDExNjcsInVzZXJuYW1lIjoic3VzYW4iLCJpc19hZG1pbiI6ZmFsc2UsInJvbGVzIjpbIm5vcm1hbF91c2VyIl19.V1sA_1d-Q0TaFl-RE1-D2AesPSrfLb568G_M_NjeOis

##返回的json
#{
   # "message": "Token revoked"
#}




#用户发出修改密码请求
@auth_bp.route('/password_reset', methods=['POST'])
def request_password_reset():
    email = request.json.get('email')
    if not email:
        return jsonify({"error": "Email is required"}), 400

    reset_data = AuthService.initiate_password_reset(email)

    # 无论用户是否存在都返回相同响应（安全考虑）
    if not reset_data:
        return jsonify({"message": "If the email exists, reset instructions have been sent"}), 200

    try:
        # 可选：后端发送邮件（如果前端不处理）
        send_reset_email(reset_data['email'], reset_data['reset_link'])
        return jsonify({"message": "Reset instructions sent"}), 200
    except Exception as e:
        current_app.logger.error(f"邮件发送失败: {str(e)}")
        return jsonify({"error": "Failed to send reset instructions"}), 500

def send_reset_email(to_email, reset_link):
    """发送密码重置邮件（可选）"""
    msg = Message(
        subject="密码重置请求",
        recipients=[to_email],
        body=f"请点击以下链接重置密码: {reset_link}",
        sender=current_app.config['MAIL_DEFAULT_SENDER']
    )
    mail.send(msg)

#发送的json
#{
   #"email": "1551406827@qq.com"
#}

#返回的json
#{
 # "message": "Reset instructions sent"
#}

#发送的邮件
#  请点击以下链接重置密码: https://your-frontend-app.com/reset-password?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXNldCI6MSwiZXhwIjoxNzUzNDMzNDM3fQ.cBvSf8wbKmiaFRecEq7A2nx3tvPOuCdSxq_DvsobBUg




#用户修改自己的密码
@auth_bp.route('/password_reset', methods=['PUT'])
def reset_password():
    try:
        # 数据验证
        data = request.get_json()
        if not data:
            return jsonify({"error": "Request body must be JSON"}), 400

        errors = password_reset_schema.validate(data)
        if errors:
            return jsonify({
                "error": "Validation failed",
                "details": errors
            }), 422  # 使用422表示语义错误

        # 调用服务层
        result = AuthService.reset_password(
            token=data['token'],
            new_password=data['new_password']
        )

        if not result.success:
            return jsonify({
                "error": result.error,
                "code": result.error_code  # 可定义具体错误代码
            }), 400

        return jsonify({
            "message": "Password updated successfully",
            "email": result.email  # 可选：返回已更新的用户邮箱
        }), 200

    except Exception as e:
        current_app.logger.error(f"Password reset error: {str(e)}")
        return jsonify({
            "error": "Internal server error"
        }), 500

# 发送的json
#{
  # "new_password": "111111",
  # "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXNldCI6MSwiZXhwIjoxNzUzNDMzNDM3fQ.cBvSf8wbKmiaFRecEq7A2nx3tvPOuCdSxq_DvsobBUg"
#}

#返回的json
#{
 # "email": "1551406827@qq.com",
  #"message": "Password updated successfully"
#}




